﻿using B.S.BasicData.Api.Write.Application.Command.Menu;
using B.S.BasicData.Domain.Entity;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.BasicData.Api.Write.Application.Handler.Menu
{
    public class DeletePathHandler : IRequestHandler<DeletePathCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PathModel> _menuRepository;

        public DeletePathHandler(IBaseRepository<PathModel> menuRepository)
        {
            _menuRepository = menuRepository;
        }

        /// <summary>
        /// 菜单删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(DeletePathCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var menus = _menuRepository.GetAll().FirstOrDefault(p=>p.Id==request.Id);
            var menu = _menuRepository.GetAll().Where(p => p.PartentId == request.Id && p.IsDelete==false).ToList();
            //有子集的时候循环删除子集和父菜单
            if (menu != null)
            {
                result.Code = StatusEnum.No;
                foreach (var item in menu)
                {
                  item.IsDelete = true;
                  if (menus != null)
                  {
                       menus.IsDelete = true;
                  }
                }
            }

            //没有子集只删除父菜单
            if (menus != null)
            {
                menus.IsDelete = true;
            }

            var res =_menuRepository.UpdateRange(menu);
            if(menus != null)
            {
                res += _menuRepository.Update(menus);
            }
            if(res>0)
            {
                result.Code = StatusEnum.OK;
                result.Data = res;
                result.Message = "删除成功";
            }
            else
            {
                result.Code = StatusEnum.Fail;
                result.Data = res;
                result.Message = "删除失败";
                
            }
            return Task.FromResult(result);
        }
    }
}
